package com.laboratory.report.lab04.lab0401;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangheng
 */
@UtilityClass
public class Lab0401Main {

    private static final String[] newLines = {
            "澳大利亚，1，2，1，4",
            "英国，1，1，0，2",
            "匈牙利，1，0，2，3",
            "比利时，1，0，1，2",
            "捷克，1，0，1，2",
            "斯洛伐克，1，0，1，2",
            "白俄罗斯，0，2，0，2",
            "西班牙，0，1，0，1",
            "乌克兰，0，1，0，1",
            "爱沙尼亚，0，0，1，1",
            "拉脱维亚，0，0，1，1",
            "波兰，0，0，1，1",
    };
    private static final URL url = Lab0401Main.class.getClassLoader().getResource("奖牌金榜.txt");
    private static final File file;
    static {
        try {
            file = new File(url.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    private static String firstLine;

    @SneakyThrows
    public static void main(String[] args) {
        List<Medal> medals = readFile();
        if(medals.size()<20) {
            wirteFile();
            medals = readFile();
        }
        System.out.println(firstLine);
        medals.stream().sorted((m1,m2)->m1.getTotal()>m2.getTotal()?-1:1).forEach(m->System.out.println(m.toLine()));
        // 修改后的文件位置是在: target/classes/奖牌金榜.txt
        wirteFile(medals);
    }

    @SneakyThrows
    private List<Medal> readFile() {
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line = firstLine = br.readLine();
            List<Medal> medals = new ArrayList<>();
            while(line!=null) {
                line = br.readLine();
                Medal medal = Medal.fromLine(line);
                if(null != medal) {
                    medals.add(medal);
                }
            }
            return medals;
        }
    }

    @SneakyThrows
    private void wirteFile() {
        try(BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)))) {
            for (String line : newLines) {
                fw.append("\n" + line);
            }
        }
    }

    @SneakyThrows
    private void wirteFile(List<Medal> datas) {
        try(BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false)))) {
            fw.write(firstLine);
            for (Medal data : datas) {
                fw.append("\n" + data.toLine());
            }
        }
    }
}
